package com.java.basis.io.bio.six;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
 * @author wangning
 * @create 2022-01-06 20:56
 */
public class ServerReaderThread extends Thread {
	private Socket socket;

	public ServerReaderThread(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		try {
			//1.从socket中获取当前客户端的输入流
			BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

			String msg;
			while ((msg = br.readLine()) != null) {
				System.out.println(msg);
				//2.服务端接收到了客户端的消息之后，是需要推送给当前所有的在线socket
				sendMsgToAllClient(msg);

			}
		} catch (Exception e) {
//			e.printStackTrace();
			System.out.println("当前有人下线");
			Server.allSocketOnline.remove(socket);

		}
	}

	/**
	 * 把当前客户端发送来的消息推送给全部在线的socket
	 * @param msg
	 */
	private void sendMsgToAllClient(String msg) throws Exception {
		for (Socket sk : Server.allSocketOnline) {
			PrintStream ps = new PrintStream(sk.getOutputStream());
			ps.println(msg);
			ps.flush();

		}
	}
}
